package com.hevery.web.async;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * @author: zhy
 * @description:
 * @date: created on 2017/10/15
 * @modified By:
 */
@RestController
public class AsyncController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MockQueue mockQueen;
    @Autowired
    private DeferredResultHolder deferredResultHolder;

    /**DeferredResult对象最红会返回一个字符串给前台，
     * 在这段代码中是看不到有另外一个线程处理任务的*/
    @RequestMapping("/order")
    public DeferredResult<String> order() throws Exception{
        logger.info("主线程开始");
        /**生成一个8位的随机数当做订单号*/
        String orderNumber = RandomStringUtils.randomNumeric(8);
        /**把订单号放到消息队列中*/
        mockQueen.setPlaceOrder(orderNumber);
        DeferredResult<String> result = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber, result);

//        Callable<String> result = new Callable<String>() {
//            @Override
//            public String call() throws Exception {
//                logger.info("副线程开始");
//                Thread.sleep(1000);
//                logger.info("副线程返回");
//                return "success";
//
//            }
//        };
        logger.info("主线程返回");
        return result;
    }
}
